/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.cms.dm.service;

import com.jeeplus.cms.util.CmsCacheUtils;
import com.jeeplus.cms.util.CmsUtils;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.cms.dm.entity.CmsDynamic;
import com.jeeplus.modules.cms.dm.mapper.CmsDynamicMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 动态表单Service
 *
 * @author Sawyer
 * @version 2020-11-21
 */
@Service
@Transactional(readOnly = true)
public class CmsDynamicService extends CrudService<CmsDynamicMapper, CmsDynamic> {

    @Override
    public CmsDynamic get(String id) {
        return super.get(id);
    }

    @Override
    public List<CmsDynamic> findList(CmsDynamic cmsDynamic) {
        return super.findList(cmsDynamic);
    }

    @Override
    public List<CmsDynamic> findAllList(CmsDynamic entity) {
        return findList(entity);
    }

    @Override
    public Page<CmsDynamic> findPage(Page<CmsDynamic> page, CmsDynamic cmsDynamic) {
        return super.findPage(page, cmsDynamic);
    }

    @Override
    @Transactional(readOnly = false)
    public void save(CmsDynamic cmsDynamic) {

        super.save(cmsDynamic);
        // 清除缓存
        CmsCacheUtils.removeCacheBySiteId(CmsCacheUtils.DYNAMIC_LIST_CACHE, cmsDynamic.getSiteId());
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(CmsDynamic cmsDynamic) {
        String siteId = get(cmsDynamic.getId()).getSiteId();
        super.delete(cmsDynamic);
        // 清除缓存
        CmsCacheUtils.removeCacheBySiteId(CmsCacheUtils.DYNAMIC_LIST_CACHE, siteId);
    }

    /**
     * 动态表单数据模型反序列化
     *
     * @param dataModel 动态表单数据模型串
     * @param mainMap   主Map，存放key和表单中文label
     * @param typeMap   表单类型Map，存放key和表单类型(支持：text、textarea、select-字典类型名、datetime、image)
     * @see dataModel的格式：{k_1:"中文名称1|表单类型1",k_2:"中文名称2|表单类型2"}
     */
    @SuppressWarnings("unchecked")
    public void modelFromJson(String dataModel, Map<String, String> mainMap, Map<String, String> typeMap) {
        String[] values;
        if (StringUtils.isNotBlank(dataModel)) {
            Map<String, String> dataModelMap = JsonMapper.getInstance().fromJson(dataModel, Map.class);
            if (dataModelMap != null) {
                for (String key : dataModelMap.keySet()) {
                    if (key.startsWith(CmsUtils.DYNAMIC_FORM_KEY_PREFIX)) {
                        values = dataModelMap.get(key).split("\\|");
                        mainMap.put(key, values.length > 0 ? values[0] : "");
                        switch (values.length) {
                            case 1: {
                                typeMap.put(key, "text");
                                break;
                            }
                            case 2: {
                                typeMap.put(key, values[1]);
                                break;
                            }
                            default: {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 动态表单数据反序列化
     *
     * @param data    Json串
     * @param dataMap 值Map，存放key和value
     * @param typeMap 表单类型Map，存放key和表单类型(支持：text、textarea、select-字典类型名、datetime、image)
     * @see data的格式：{k_1:"值1",k_2:"值1"}
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> dataFromJson(String data, Map<String, String> typeMap) {
        if (StringUtils.isBlank(data)) {
            return new HashMap<>(16);
        }
        Map<String, Object> dataMap = new HashMap<>(16);
        dataMap = JsonMapper.getInstance().fromJson(data, Map.class);
        //处理typeMap中要求显示日期表单，而dataMap中存储非日期类型的值（存储值后修改表单类型）
        //修正图片路径
        if (null != typeMap && null != dataMap) {
            for (String key : typeMap.keySet()) {
                if ("datetime".equals(typeMap.get(key))) {
                    //非时间格式则重新赋空值
                    Date date = DateUtils.parseDate(dataMap.get(key));
                    if (null == date) {
                        dataMap.put(key, "");
                    } else {
                        dataMap.put(key, date);
                    }
                }
                if ("image".equals(typeMap.get(key))) {
                    dataMap.put(key, CmsUtils.correctFileUrl((String) dataMap.get(key)));
                }
            }
        }
        return dataMap;
    }

    /**
     * 动态表单数据序列化
     */
    @SuppressWarnings("rawtypes")
    public String dataToJson(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<String, String>();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            if (paramName.startsWith(CmsUtils.DYNAMIC_FORM_KEY_PREFIX)) {
                String[] paramValues = request.getParameterValues(paramName);
                if (paramValues.length == 1) {
                    String paramValue = paramValues[0];
                    if (StringUtils.isNotBlank(paramValue)) {
                        map.put(paramName, paramValue);
                    }
                }
            }
        }
        return JsonMapper.getInstance().toJson(map);
    }

}
